﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows8Accelerator.Core.Xaml.Html;

namespace Windows8Accelerator.Core.Xaml.Controls.RichText
{
    public class ImageVisitor : ContentVisitor
    {
        public ImageVisitor(SuperHtmlNode superHtmlNode, SuperHtmlNodeVisitor parentVisitor)
            : base(superHtmlNode, parentVisitor)
        {
            VisitChildren = false;
        }

        protected override void InternalVisitNode1(SuperHtmlNode htmlNode)
        {
            if (htmlNode.Attributes.ContainsKey("src"))
            {
                AddLineBreakingIfNecessary();
                if (State.RequiresLeadingSpace && State.HasContent)
                {
                    AddRun(" ");
                }                

                double? width = null;
                double? height = null;
                if (htmlNode.Attributes.ContainsKey("width"))
                {
                    double d = 0;
                    if (double.TryParse(htmlNode.Attributes["width"], NumberStyles.Number, CultureInfo.InvariantCulture, out d))
                        width = d;
                }
                if (htmlNode.Attributes.ContainsKey("height"))
                {
                    double d = 0;
                    if (double.TryParse(htmlNode.Attributes["height"], NumberStyles.Number, CultureInfo.InvariantCulture, out d))
                        height = d;
                }

                AdjustSize(ref width, State.MaxWidth, ref height);
                AdjustSize(ref height, State.MaxHeight, ref width);

                var imageSrc = htmlNode.Attributes["src"];

                AddImage(imageSrc, width, height);
            }

        }

        private void AdjustSize(ref double? mainValue, double maxValue, ref double? secondaryValue)
        {
            if (mainValue.HasValue && mainValue.Value >= maxValue)
            {
                var ratio = maxValue / mainValue;
                mainValue = maxValue;
                if (secondaryValue.HasValue)
                {
                    secondaryValue = secondaryValue.Value * ratio;
                }
            }
        }
    }
}
